package com.example.kt_fast.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.example.kt_common.util.Constants
import com.example.kt_fast.R
import com.example.kt_fast.bean.FastBean

/**
 * Created by 小陈 on 2025/3/24.
 * Time: 21:48.
 */
class FastRVAdapter(var listener: FastItemClickListener) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>(), OnClickListener {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return ViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.item_fast_rv, parent, false)
        )
    }

    override fun getItemCount(): Int {
        return diff.currentList.size

    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val data = diff.currentList[position]
        (holder as ViewHolder).title.text = data.title
        holder.img.load(data?.imgRes!!)
        holder.cv_carView.setOnClickListener(this)
        holder.cv_carView.tag = position
    }

    private var lastClickTime: Long = 0
    override fun onClick(v: View?) {
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastClickTime > Constants.MIN_CLICK_DELAY_TIME && v != null) {
            lastClickTime = currentTime
            listener.onItemClick(v.tag as Int)
        }
    }

    class ViewHolder(item: View) : RecyclerView.ViewHolder(item) {
        var img: ImageView = item.findViewById(R.id.iv_img)
        var title: TextView = item.findViewById(R.id.tv_text)
        var cv_carView: CardView = item.findViewById(R.id.cv_carView)
    }

    private var diff: AsyncListDiffer<FastBean>

    init {
        diff = AsyncListDiffer(this, MyCallback())
    }

    fun setData(list: List<FastBean>?) {
        //AsyncListDiffer需要一个新数据，不然添加无效
        diff.submitList(if (list != null) ArrayList(list) else null)
    }

    class MyCallback : DiffUtil.ItemCallback<FastBean>() {
        override fun areItemsTheSame(
            oldItem: FastBean, newItem: FastBean
        ): Boolean {
            return oldItem == newItem
        }

        override fun areContentsTheSame(
            oldItem: FastBean, newItem: FastBean
        ): Boolean {
            return oldItem == newItem
        }
    }

}